package com.lgy.springboot_example.request_validate;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class PermissionInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            RequestPermission requestPermission = handlerMethod.getMethod().getAnnotation(RequestPermission.class);
            if (requestPermission == null)
                return true;
            String token = request.getHeader("token");
            if (StringUtils.isEmpty(token))
                return doEnd(response);
            String roleLevel = requestPermission.value().getRoleLevel();
            return this.doHeader(token, roleLevel, response);
        }
        return true;
    }

    /**
     * 权限校验
     *
     * @param token
     * @param roleLevel
     * @param response
     * @return
     */
    public boolean doHeader(String token, String roleLevel, HttpServletResponse response) {

        String data = redisTemplate.opsForValue().get(token);
        if (StringUtils.isEmpty(data))
            return doEnd(response);

        //用户有操作时，初始化redis过期时间
        //redisTemplate.opsForValue().set(token, data, 30 * 60, TimeUnit.SECONDS);

        JSONObject json = JSONObject.parseObject(data);
        JSONObject jo = json.getJSONObject("role");
        if (jo.getInteger(roleLevel) < 0)
            return doEnd(response);
        return true;
    }

    public boolean doEnd(HttpServletResponse response) {
        JSONObject data = new JSONObject();
        data.put("message", "您的权限不足！");
        response.setStatus(401);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.println(data);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null)
                writer.close();
        }
        return false;
    }
}
